<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择商品分类" clearable>
          <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName"
            :value="category.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择商品类型" clearable>
          <el-option v-for="dict in dict.type.good_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否显示" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否显示" clearable>
          <el-option v-for="dict in dict.type.sys_show_hide" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['hotel:good:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['hotel:good:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['hotel:good:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hotel:good:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="id" />
      <el-table-column label="商品分类" align="center" prop="categoryId">
        <template slot-scope="scope">
          <span v-if="scope.row.categoryId">{{ categoryList.find(item => item.id === scope.row.categoryId).categoryName
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="已售数量" align="center" prop="sold" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="商品类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.good_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="起购数量" align="center" prop="minimum" />
      <el-table-column label="商品规格" align="center" prop="specs" />
      <el-table-column label="限购数量" align="center" prop="limitNum" />
      <el-table-column label="显示排序" align="center" prop="orderNum" />
      <el-table-column label="是否显示" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_show_hide" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['hotel:good:edit']">修改</el-button>
          <el-button v-if="scope.row.type === '4'" size="mini" type="text" icon="el-icon-edit" @click="handleOpenUnit(scope.row)">规格</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['hotel:good:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择商品分类">
                <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName"
                  :value="category.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品图片" prop="image">
              <image-upload v-model="form.image" label="商品图片" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="已售数量" prop="sold">
              <el-input v-model="form.sold" placeholder="请输入已售数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_show_hide" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择商品类型">
                <el-option v-for="dict in dict.type.good_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === '2'">
            <el-form-item label="起购数量" prop="minimum">
              <el-input-number v-model="form.minimum" placeholder="请输入起购数量"   controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === '3'">
            <el-form-item label="限购数量" prop="limitNum">
              <el-input-number v-model="form.limitNum" placeholder="请输入限购数量"  controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="规格信息" :visible.sync="unitTableOpen" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddUnit">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
        </el-col>
      </el-row>

      <el-table v-if="refreshTable" v-loading="unitLoading" :data="unitList" row-key="id"
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="规格名称" align="center" prop="name" />
        <el-table-column label="规格价格" align="center" prop="price" />
        <el-table-column label="显示排序" align="center" prop="orderNum" />
        <el-table-column label="是否显示" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_show_hide" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateUnit(scope.row)"
              >修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAddUnit(scope.row)"
             v-if="scope.row.parentId === 0" >新增</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteUnit(scope.row)"
              >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeUnitTable">关 闭</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="title" :visible.sync="unitOpen" width="500px" append-to-body>
      <el-form ref="unitForm" :model="unitForm" :rules="unitRules" label-width="80px">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="unitForm.name" placeholder="请输入规格名称" />
        </el-form-item>
        <el-form-item label="规格价格" prop="price">
          <el-input v-model="unitForm.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="unitForm.orderNum" placeholder="请输入序号" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="是否显示" prop="status">
          <el-radio-group v-model="unitForm.status">
            <el-radio v-for="dict in dict.type.sys_show_hide" :key="dict.value" :label="dict.value">{{ dict.label
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUnitForm">确 定</el-button>
        <el-button @click="cancelUnit">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGood, getGood, delGood, addGood, updateGood } from "@/api/hotel/good";
import { listCategory } from "@/api/hotel/category";
import { listUnit, getUnit, delUnit, addUnit, updateUnit } from "@/api/hotel/unit";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Good",
  components: {
    Treeselect
  },
  dicts: ['good_type', 'sys_show_hide'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 商品分类列表
      categoryList: [],
      // 子表选中数据
      checkedRsGoodUnit: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodList: [],
      // 商品规格表格数据
      rsGoodUnitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        image: null,
        name: null,
        sold: null,
        price: null,
        type: null,
        minimum: null,
        specs: null,
        limitNum: null,
        categoryId: null,
        orderNum: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 商品id
      goodId: null,
      // 规格表格是否显示
      unitTableOpen: false,
      // 遮罩层
      unitLoading: true,
      // 商品规格表格数据
      unitList: [],
      // 商品规格树选项
      unitOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      unitOpen: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 表单参数
      unitForm: {},
      // 表单校验
      unitRules: {
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listGood(this.queryParams).then(response => {
        this.goodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询商品分类列表 */
    getCategoryList() {
      listCategory().then(response => {
        this.categoryList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        image: null,
        name: null,
        sold: null,
        price: null,
        type: null,
        minimum: null,
        specs: null,
        limitNum: null,
        categoryId: null,
        orderNum: null
      };
      this.rsGoodUnitList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGood(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.rsGoodUnitList = this.rsGoodUnitList;
          if (this.form.id != null) {
            updateGood(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGood(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function () {
        return delGood(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
     /** 导出按钮操作 */
    handleExport() {
      this.download('hotel/good/export', {
        ...this.queryParams
      }, `good_${new Date().getTime()}.xlsx`)
    },


    /** 查询商品规格列表 */
    getUnitList() {
      this.unitLoading = true;
      const queryParams = {
        goodId: this.goodId
      }
      listUnit(queryParams).then(response => {
        this.unitList = this.handleTree(response.data, "id", "parentId");
        this.unitLoading = false;
      });
    },
    /** 转换商品规格数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询商品规格下拉树结构 */
    getTreeselect() {
      listUnit().then(response => {
        this.unitOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.unitOptions.push(data);
      });
    },
    // 取消按钮
    unitCancel() {
      this.unitOpen = false;
      this.reset();
    },
    // 表单重置
    unitReset() {
      this.unitForm = {
        id: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        name: null,
        price: null,
        orderNum: null,
        goodId: this.goodId,
        parentId: null
      };
      this.resetForm("unitForm");
    },
    /** 新增按钮操作 */
    handleAddUnit(row) {
      this.unitReset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.unitForm.parentId = row.id;
      } else {
        this.unitForm.parentId = 0;
      }
      this.unitOpen = true;
      this.title = "添加商品规格";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdateUnit(row) {
      this.unitReset();
      this.getTreeselect();
      if (row != null) {
        this.unitForm.parentId = row.parentId;
      }
      getUnit(row.id).then(response => {
        this.unitForm = response.data;
        this.unitOpen = true;
        this.title = "修改商品规格";
      });
    },
    /** 提交按钮 */
    submitUnitForm() {
      this.$refs["unitForm"].validate(valid => {
        if (valid) {
          if (this.unitForm.id != null) {
            updateUnit(this.unitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.unitOpen = false;
              this.getUnitList();
            });
          } else {
            this.unitForm.goodId = this.goodId;
            addUnit(this.unitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.unitOpen = false;
              this.getUnitList();
            });
          }
        }
      });
    },
    cancelUnit() {
      this.unitOpen = false;
    },
    /** 删除按钮操作 */
    handleDeleteUnit(row) {
      this.$modal.confirm('是否确认删除商品规格编号为"' + row.id + '"的数据项？').then(function () {
        return delUnit(row.id);
      }).then(() => {
        this.getUnitList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 打开规格表格 */
    handleOpenUnit(row) {
      this.unitTableOpen = true;
      this.goodId = row.id;
      this.getUnitList();
    },
    /** 关闭规格表格 */
    closeUnitTable() {
      this.unitTableOpen = false;
    }
  }
};
</script>
